<template>
  <el-drawer
      v-model="drawerVisible"
      title="商家评价"
      direction="rtl"
      size="50%"
      class="reviews-drawer"
  >
    <div class="reviews-container">
      <!-- 评分概览 -->
      <div class="score-overview" v-if="sjpf !== null">
        <div class="score-main">
          <div class="score-value">
            <span>{{ sjpf }}</span>
            <div class="score-label">综合评分</div>
          </div>
          <div class="star-rating">
            <el-rate
                :model-value="Math.round(sjpf)"
                disabled
                :colors="['#ff9500', '#ff9500', '#ff9500']"
                size="large"
            />
            <div class="rating-text">{{ Math.round(sjpf) }}星</div>
          </div>
        </div>

        <div class="reviews-summary">
          <el-progress
              :percentage="positiveReviewPercentage"
              :stroke-width="12"
              :show-text="false"
              color="#67c23a"
              class="progress-bar"
          />
          <div class="summary-text">
            <span>{{ positiveReviewPercentage }}%的好评率</span>
            <span class="review-count">({{ reviewsCount }}条评论)</span>
          </div>
        </div>
      </div>

      <!-- 评价筛选 -->
      <div class="reviews-filter">
        <el-radio-group v-model="filterType" size="small" class="filter-group">
          <el-radio-button label="all">全部({{ allReviews.length }})</el-radio-button>
          <el-radio-button label="positive">好评({{ positiveReviews.length }})</el-radio-button>
          <el-radio-button label="negative">差评({{ negativeReviews.length }})</el-radio-button>
          <el-radio-button label="with-image">有图({{ imageReviews.length }})</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 评价列表 -->
      <div class="reviews-list">
        <div
            v-for="item in filteredReviews"
            :key="item.ddid"
            class="review-item"
        >
          <div class="review-header">
            <div class="user-info">
              <el-avatar
                  :src="item.yhtx ? url + item.yhtx : ''"
                  size="small"
                  class="user-avatar"
              >
                <el-icon v-if="!item.yhtx"><User /></el-icon>
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ item.yhnc || '匿名用户' }}</div>
                <div class="review-time">{{ formatTime(item.pjsj) }}</div>
              </div>
            </div>
            <el-rate
                :model-value="parseInt(item.sjpf) || 0"
                disabled
                :colors="['#ff9500', '#ff9500', '#ff9500']"
                size="small"
            />
          </div>

          <div class="review-content">
            {{ item.pjnr }}
          </div>

          <div class="review-images" v-if="item.sctp">
            <el-image
                v-for="(img, index) in parseImages(item.sctp)"
                :key="index"
                :src="url+img"
                class="review-image"
                :preview-src-list="parseImages(item.sctp)"
                :initial-index="index"
                fit="cover"
                lazy
            />
          </div>

          <div class="review-footer">
            <div class="review-actions">
              <el-button type="primary" link>
                <el-icon><ChatLineRound /></el-icon>
                回复
              </el-button>
            </div>
          </div>
        </div>

        <div class="no-reviews" v-if="filteredReviews.length === 0">
          <el-icon class="empty-icon"><Document /></el-icon>
          <p>暂无评价</p>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import {computed, defineExpose, ref, watch} from "vue"
import axios from "axios"
import {ChatLineRound, Document, User} from '@element-plus/icons-vue'

const drawerVisible = ref(false)
const sjid = ref(0);    //商家id
const sjpf = ref(0);    //商家评分
const sjpj = ref([]);   //评价信息（数组）
const filterType = ref('all')
const url = ref('http://localhost:8088/team/upload/')

// 获取所有评价信息
const getPingLuns = async () => {
  try {
    const {data} = await axios.get(`/api/pingjia/sjplq/${sjid.value}`);
    if(data.code === 200){
      sjpj.value = data.data;
      console.log(sjpj.value);
    }
  } catch (error) {
    console.error('获取评价信息失败:', error)
  }
}

//获取商家评分
const getPinFen = async () => {
  try {
    const {data} = await axios.get(`/api/pingjia/sjpj/${sjid.value}`);
    if(data.code === 200){
      sjpf.value = data.data;
    }
  } catch (error) {
    console.error('获取商家评分失败:', error)
  }
}

//获取商家id，通过商家id来计算评分
const handlePingLunData = async (obj) => {
  sjid.value = obj;
  await getPinFen();
  await getPingLuns();
  drawerVisible.value = true;
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 解析图片URL
const parseImages = (imageString) => {
  if (!imageString) return []
  return imageString.split(',').filter(url => url.trim() !== '')
}

// 所有评价
const allReviews = computed(() => {
  return sjpj.value || []
})

// 有效评价数量
const reviewsCount = computed(() => {
  return allReviews.value.length
})

// 好评（3星及以上）
const positiveReviews = computed(() => {
  return allReviews.value.filter(item => {
    const rating = parseInt(item.sjpf)
    return !isNaN(rating) && rating >= 3
  })
})

// 差评（2星及以下）
const negativeReviews = computed(() => {
  return allReviews.value.filter(item => {
    const rating = parseInt(item.sjpf)
    return !isNaN(rating) && rating <= 2
  })
})

// 有图评价
const imageReviews = computed(() => {
  return allReviews.value.filter(item => item.sctp && item.sctp.trim() !== '')
})

// 过滤评价
const filteredReviews = computed(() => {
  switch (filterType.value) {
    case 'positive':
      return positiveReviews.value
    case 'negative':
      return negativeReviews.value
    case 'with-image':
      return imageReviews.value
    default:
      return allReviews.value
  }
})

// 好评率
const positiveReviewPercentage = computed(() => {
  if (allReviews.value.length === 0) return 0
  const positiveCount = positiveReviews.value.length
  return Math.round((positiveCount / allReviews.value.length) * 100)
})

// 监听筛选类型变化，确保正确更新
watch(filterType, (newVal) => {
  // 这里可以添加额外的处理逻辑，如果需要的话
  console.log('筛选类型已更改为:', newVal);
})

// 暴露给父组件
defineExpose({
  handlePingLunData
})
</script>

<style scoped>
.reviews-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #eee;
  font-size: 1.2rem;
  font-weight: 600;
}

.reviews-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.score-overview {
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  margin: 0 20px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.score-main {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 20px;
}

.score-value {
  text-align: center;
}

.score-value span {
  font-size: 3rem;
  font-weight: 700;
  color: #ff6b35;
  line-height: 1;
}

.score-label {
  font-size: 0.9rem;
  color: #666;
  margin-top: 5px;
}

.star-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.rating-text {
  font-size: 1rem;
  font-weight: 600;
  color: #333;
}

.reviews-summary {
  display: flex;
  align-items: center;
  gap: 15px;
}

.progress-bar {
  flex: 1;
  max-width: 200px;
}

.summary-text {
  font-size: 0.9rem;
  color: #666;
}

.review-count {
  color: #999;
  margin-left: 5px;
}

.reviews-filter {
  padding: 0 20px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-group :deep(.el-radio-button__inner) {
  border-radius: 20px !important;
  margin: 0 5px;
  border: 1px solid #dcdfe6 !important;
}

.filter-group :deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 20px !important;
  margin-left: 0;
}

.filter-group :deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 20px !important;
}

.filter-group :deep(.is-active .el-radio-button__inner) {
  background: #409eff;
  border-color: #409eff !important;
  color: white;
}

.reviews-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.review-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.review-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  background-color: #409eff;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
}

.review-time {
  font-size: 0.8rem;
  color: #999;
}

.review-content {
  color: #333;
  line-height: 1.6;
  margin-bottom: 15px;
  font-size: 0.95rem;
}

.review-images {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;
  border: 1px solid #f0f0f0;
}

.review-image:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.review-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.review-actions {
  display: flex;
  gap: 10px;
}

.no-reviews {
  text-align: center;
  padding: 50px 20px;
  color: #999;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 20px;
  color: #c0c4cc;
}
</style>
